package org.syndicate.domain;

import java.util.List;

import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;

/**
 * Facility of syndicated loan.<br/>
 * A facility is a commitment by a company to lend.
 * 
 * @author akiraabe
 */
@RooJavaBean
@RooToString
@RooEntity(inheritanceType = "JOINED")
public class Facility extends AbstractPosition {

	private Double limit;

	private Double feeAmount;
	
	private Double balanceAmount;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void apply(AbstractTransaction transaction) {

		if ("FacilityInvestment".equals(transaction.getDiscriminator())) {
			this.setLimit(transaction.getAmount());
			this.setBalanceAmount(transaction.getAmount());
			this.setFeeAmount(0.0);
			this.setName(transaction.getName());

			// create SharePie
			SharePie newSharePie = transaction.getSharePie()
					.prorate(getLimit());
			newSharePie.setName("Auto generated by facility investment.");
			newSharePie.persist();

			this.setSharePie(transaction.getSharePie());
			this.setName(transaction.getName());
			this.setDiscriminator("Facility");

			// TODO quick & dirty code!!!
			transaction.setSharePie(newSharePie);
		}
		
		if ("FeePayment".equals(transaction.getDiscriminator())) {
			addFeeAmount(transaction.getAmount());

			// create SharePie
			SharePie newSharePie = this.getSharePie()
					.prorate(transaction.getAmount());
			newSharePie.setName("Auto generated by fee payment.");
			newSharePie.persist();

//			setSharePie(transaction.getSharePie());

			// TODO quick & dirty code!!!
			transaction.setSharePie(newSharePie);
		}
		
		if ("Drawdown".equals(transaction.getDiscriminator())) {
			reduceBalanceAmount(transaction.getAmount());
		}

		// Debug.
		System.out.println("Facility#apply");
		System.out.println(getSharePie());
		for (Share share : getSharePie().getShares()) {
			System.out.println("  " + share);
		}
	}

	public void transfer(Company from, Company to, Double percent) {
		System.out.println("Facility#transfer");
	}
	
	/**
	 * Find facility by share pie.
	 * 
	 * TODO Need SharePie : Facilty = 1 : 1 !!!
	 * @param sharePie
	 * @return facility related sharePie.
	 */
	static Facility findBySharePie(SharePie sharePie) {
		Facility result = null;
		List<Facility> facilities = Facility.findAllFacilitys();
		for (Facility facility : facilities) {
			if (sharePie.equals(facility.getSharePie())) {
				System.out.println("DEBUG => " + facility);
				result = facility;
			}
		}
		return result;
	}
	
	private void addFeeAmount(Double amount) {
		setFeeAmount(getFeeAmount() + amount);
	}
	
	private void reduceBalanceAmount(Double amount) {
		if (amount > this.getBalanceAmount()) {
			throw new RuntimeException();
		}
		setBalanceAmount(getBalanceAmount() - amount);
	}
	
	
}


